package me.jollyfly.jshop.user.server.service.impl

import me.jollyfly.jshop.common.bean.ResultBean
import me.jollyfly.jshop.user.client.model.UserDO
import me.jollyfly.jshop.user.server.StringUserTokenFactory
import me.jollyfly.jshop.user.server.dao.UserDAO
import me.jollyfly.jshop.user.server.service.UserService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.redis.core.RedisTemplate
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.util.concurrent.TimeUnit

/**
 * @author jollyfly
 */


@Service
open class UserServiceImpl @Autowired
constructor(private val userDAO: UserDAO) : UserService {


    @Autowired
    private var userRedisTemplate: RedisTemplate<String, Any>? = null

    override fun getByUsername(username: String?): UserDO {
        val userDO = UserDO()
        userDO.username = username
        return this.userDAO.selectOne(userDO)
    }

    override fun register(userDO: UserDO) {

    }

    /**
     * 登录业务
     *
     * @param userDO 用户实体
     *
     * @return 生成的令牌
     */

    @Transactional(readOnly = true)
    override fun login(userDO: UserDO): ResultBean<String> {
        val userResult = userDAO.selectOne(userDO)
                ?: return ResultBean(null, ResultBean.FAIL, "用户名或密码错误")
        val token = StringUserTokenFactory.createToken(userResult)
        this.userRedisTemplate!!.opsForValue().set(token, userResult, 1, TimeUnit.DAYS)
        return ResultBean(token)
    }


}
